import os.path
import sys
import pub_ssh

CURR_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def single_install(redis_dict):
    # 单独读yaml
    # conf_path = f'conf{os.sep}deploy_redis.yml'
    # rc = pub_readconf.ReadConf(os.path.join(CURR_PATH, conf_path))
    # redis_rc = rc.read_yaml()

    host_ip = redis_dict['host_ip']
    host_port = redis_dict['host_port']
    host_username = redis_dict['host_username']
    host_password = redis_dict['host_password']
    redis_path = redis_dict['redis_path']
    redis_port = redis_dict['redis_port']
    redis_pwd = redis_dict['redis_pwd']

    redis_client = pub_ssh.SSHClient(hostname=host_ip, port=host_port, username=host_username, password=host_password)
    # 连接ssh
    redis_client.conn()
    # 检查端口
    redis_port_exist = redis_client.check_port(redis_port)
    # 检查目录
    root_path = os.path.dirname(redis_path)
    src_file = os.path.join(CURR_PATH, 'package/redis7.tar.gz')
    dest_file = os.path.join(root_path, 'redis7.tar.gz').replace(os.sep, "/")

    # # 连接sftp
    redis_client.sftp_conn()
    # 判断redis目录存在
    redis_path_exist = redis_client.sftp_check_path(redis_path)

    if redis_port_exist and redis_path_exist:
        # 上传文件
        redis_client.sftp_upload_file(src_file, dest_file)
        # 在远程服务器上解压文件
        result = redis_client.run(f'tar -zxvf {dest_file} -C {root_path}')
        if result['stderr'] == '':
            print(f"文件在远程目录 {root_path} 中解压成功。")

            # 更换配置文件
            conf_path = os.path.join(redis_path, 'conf/redis.conf').replace(os.sep, '/')
            print("Redis配置文件：", conf_path)
            redis_conf_data_str = redis_client.read_remote_file(conf_path)
            replacements = {
                "127.0.0.1": host_ip,
                "6379": redis_port,
                "123456": redis_pwd,
                "root_path": redis_path
            }
            for old, new in replacements.items():
                redis_conf_data_str = redis_conf_data_str.replace(old, str(new))
            print(redis_conf_data_str)
            redis_client.write_remote_file(conf_path, redis_conf_data_str)
            print(f"更换{conf_path}成功")

            # 更换启动脚本
            redis_script = os.path.join(redis_path, 'redis.sh').replace(os.sep, '/')
            print("Redis脚本文件：", redis_script)
            redis_script_data_str = redis_client.read_remote_file(redis_script)
            replacement = {
                "6379": redis_port,
                "root_path": redis_path
            }
            for old, new in replacement.items():
                redis_script_data_str = redis_script_data_str.replace(old, str(new))
            redis_client.write_remote_file(redis_script, redis_script_data_str)
            res = redis_client.run(f"chmod +x {redis_script} && sh {redis_script} start")
            if res['stderr'] == '':
                print("redis部署成功")
                print(f"redis连接命令：redis-cli -h {host_ip} -p {redis_port} -a '{redis_pwd}'")
            else:
                print("redis部署失败")

    redis_client.sftp_close()
    redis_client.ssh_close()


def cluster_install(redis_info_list):
    # 循环信息
    for redis_item in redis_info_list:
        # 定义变量
        host_ip = redis_item['host_ip']
        host_port = redis_item['host_port']
        host_username = redis_item['host_username']
        host_password = redis_item['host_password']
        redis_path = redis_item['redis_path']
        cluster_port = redis_item['cluster_port']
        redis_pwd = redis_item['redis_pwd']

        redis_client = pub_ssh.SSHClient(hostname=host_ip, port=host_port, username=host_username,
                                         password=host_password)
        # 连接ssh
        redis_client.conn()
        # 检查端口
        redis_port_exist = redis_client.check_port(int(cluster_port))
        # 检查目录
        root_path = os.path.dirname(redis_path)
        src_file = os.path.join(CURR_PATH, 'package/redis7.tar.gz')
        dest_file = os.path.join(root_path, 'redis7.tar.gz').replace(os.sep, "/")

        # # 连接sftp
        redis_client.sftp_conn()
        # 判断redis目录存在
        redis_path_exist = redis_client.sftp_check_path(redis_path)

        # 如果端口没占用和目录没存在
        if redis_port_exist and redis_path_exist:
            # 上传文件
            redis_client.sftp_upload_file(src_file, dest_file)
            # 在远程服务器上解压文件
            result = redis_client.run(f'tar -zxvf {dest_file} -C {root_path}')
            if result['stderr'] == '':
                print(f"文件在远程目录 {root_path} 中解压成功。")

            # 删除包
            result = redis_client.run(f'rm -rf {dest_file}')
            if result['stderr'] == '':
                print(f"删除 {dest_file} 成功。")

            result = redis_client.run(f'mv {root_path}/redis {redis_path}')
            if result['stderr'] == '':
                print(f"更改目录为 {redis_path} 成功。")

            # 更换配置文件
            conf_path = os.path.join(redis_path, 'conf/redis.conf').replace(os.sep, '/')
            print("Redis配置文件：", conf_path)
            redis_conf_data_str = redis_client.read_remote_file(conf_path)
            replacements = {
                "127.0.0.1": host_ip,
                "6379": cluster_port,
                "123456": redis_pwd,
                "root_path": redis_path,
                "#cluster": "cluster"
            }
            for old, new in replacements.items():
                redis_conf_data_str = redis_conf_data_str.replace(old, str(new))
            print(redis_conf_data_str)
            redis_client.write_remote_file(conf_path, redis_conf_data_str)
            print(f"更换{conf_path}成功")

            # 更换启动脚本
            redis_script = os.path.join(redis_path, 'redis.sh').replace(os.sep, '/')
            print("Redis脚本文件：", redis_script)
            redis_script_data_str = redis_client.read_remote_file(redis_script)
            replacement = {
                "6379": cluster_port,
                "root_path": redis_path
            }
            for old, new in replacement.items():
                redis_script_data_str = redis_script_data_str.replace(old, str(new))
            redis_client.write_remote_file(redis_script, redis_script_data_str)
            res = redis_client.run(f"chmod +x {redis_script} && sh {redis_script} start")
            if res['stderr'] == '':
                print("redis部署成功")
                print(f"redis连接命令：redis-cli -h {host_ip} -p {cluster_port} -a '{redis_pwd}'")
            else:
                print("redis部署失败")

        redis_client.sftp_close()
        redis_client.ssh_close()

    # 创建集群
    for redis_item in redis_info_list:
        # 定义变量
        host_ip = redis_item['host_ip']
        host_port = redis_item['host_port']
        host_username = redis_item['host_username']
        host_password = redis_item['host_password']
        redis_path = redis_item['redis_path']
        redis_pwd = redis_item['redis_pwd']
        nodes = redis_item['nodes']

        nodes_str = ""
        for node in nodes:
            nodes_str += node + ' '

        redis_client = pub_ssh.SSHClient(hostname=host_ip, port=host_port, username=host_username,
                                         password=host_password)
        # 连接ssh
        redis_client.conn()

        redis_cli_path = os.path.join(redis_path, 'bin/redis-cli').replace(os.sep, '/')
        print(f"echo yes | {redis_cli_path} --cluster create {nodes_str} --cluster-replicas 1 -a {redis_pwd}")
        res = redis_client.run(
            f"echo yes | {redis_cli_path} --cluster create {nodes_str} --cluster-replicas 1 -a {redis_pwd} --no-auth-warning")
        print(res)
        if res['stderr'] == '':
            print("redis集群部署成功")
            print(f"redis连接命令：redis-cli -h {host_ip} -c -a '{redis_pwd}'")
            sys.exit(0)
        else:
            print("redis集群部署失败")

        redis_client.sftp_close()
        redis_client.ssh_close()
        sys.exit(1)
